package source;

import global.JDefined;
import global.method_static;
import global.var_static;

import java.applet.Applet;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JApplet;

public class AppletGame extends Panel implements MouseListener {
	StringBuffer strBffer;
	private State_Temp m_StateTemp;
	private long m_lBeginTime;
	private long m_lEndTime;
	private long m_lCycle;
	public AppletGame() {
		init();
		addMouseListener(this);
	}
	public void init(){
		StateMachineInit();
	}
	public void run(){
		while(true){
			m_lBeginTime = System.currentTimeMillis();
			updateApplet();
			paintApplet();
			m_lEndTime = System.currentTimeMillis();
	        if (m_lEndTime - m_lCycle > 1000) {
	            m_lCycle = System.currentTimeMillis();
	        } else {
	        }
	        CountFPS();
		}
        
	}
	//TODO: Calculator FPS

    public void CountFPS() {
        long iDeltaTime = m_lEndTime - m_lBeginTime;
        if (iDeltaTime < var_static.s_iFrameLimitTimer) {
            try {
                Thread.sleep(var_static.s_iFrameLimitTimer - iDeltaTime);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
	public void updateApplet(){
		StateMachineUpdate();
	}
	public void paintApplet(){

	}
	public void update(Graphics g){
		StateMachinePaint();
	}
	//Overide method Applet
	public void paint(Graphics g){
		var_static.s_graphics = getGraphics();
		update(var_static.s_graphics);
	}
	//Method handle for App
	public void StateMachineInit(){
		m_StateTemp = new State_Temp();
		m_StateTemp.init();
		var_static.s_iFrameLimitTimer = 1000/JDefined.FPS_NUMBER;
	}
	public void StateMachineUpdate(){
		StateMachineMessage(JDefined.MESSAGE_UPDATE);
	}
	public void StateMachinePaint(){
		StateMachineMessage(JDefined.MESSAGE_PAINT);
		
	}
	public void StateMachineMessage(int mess){
		switch (var_static.s_curState) {
			case JDefined.STATE_TEMP:
				m_StateTemp.handle(mess);
				break;
		}
	}
	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		var_static.s_posX = arg0.getX();
		var_static.s_posY = arg0.getY();
		method_static.addBall(var_static.s_arrayBox);
		repaint();
	} 

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
	}

}
